#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time    : 2025/5/9 15:19
@Author  : HZP
@File    : middleware.py
"""
from dataclasses import dataclass
from typing import Optional

from flask import Request
from injector import inject

from internal.exception.exception import UnauthorizedException
from internal.model import Account
from internal.service import JwtService, AccountService


@inject
@dataclass
class Middleware:
    jwt_service: JwtService
    account_service: AccountService

    def request_loader(self, request: Request) -> Optional[Account]:
        if request.blueprint == "llmops":
            # 获取token
            access_token = self._validate_credential(request)
            # 解析token 数据
            payload = self.jwt_service.parse_token(access_token)
            # 获取用户信息
            account_id = payload.get("sub")
            return self.account_service.get_account(account_id)

    @classmethod
    def _validate_credential(cls, request: Request) -> str:
        # 获取接口头信息
        auth_header = request.headers.get('Authorization')
        # 判断是否为none “” []
        if not auth_header:
            raise UnauthorizedException("该接口需要授权才能访问，请登录后尝试")
        # 判断是否为空格
        if " " not in auth_header:
            raise UnauthorizedException("该接口需要授权才能访问，验证格式失败")
        # 分割获取授权信息，必须 Bearer access_token
        auth_schema, access_token = auth_header.split(None, 1)
        if auth_schema.lower() != 'bearer':
            raise UnauthorizedException("该接口需要授权才能访问，验证格式失败")
        return access_token
